package com.ssyc.gsk_tk.activity;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.manager.TimerCountManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.gsk_tk.R;
import com.ssyc.gsk_tk.adapter.PanelGvAdapter;
import com.ssyc.gsk_tk.bean.ArticleInfo;
import com.ssyc.gsk_tk.bean.BlankInfo;
import com.ssyc.gsk_tk.bean.CommitAnswerInfo;
import com.ssyc.gsk_tk.bean.CommitInfo;
import com.ssyc.gsk_tk.bean.GapFillingInfo;
import com.ssyc.gsk_tk.bean.OverQuestion;
import com.ssyc.gsk_tk.bean.PanelInfo;
import com.ssyc.gsk_tk.bean.QuestionInfo;
import com.ssyc.gsk_tk.bean.ReadInfo;
import com.ssyc.gsk_tk.bean.SentenceInfo;
import com.ssyc.gsk_tk.bean.TkHomeWorkInfo;
import com.ssyc.gsk_tk.fragment.TkChooseWordInArticleFragment;
import com.ssyc.gsk_tk.fragment.TkClozeTestFragment;
import com.ssyc.gsk_tk.fragment.TkGapFillingFragment;
import com.ssyc.gsk_tk.fragment.TkReadFragment;
import com.ssyc.gsk_tk.fragment.TkSentenceChangeErrorFragment;
import com.ssyc.gsk_tk.fragment.TkSingleChoiceFragment;
import com.ssyc.gsk_tk.fragment.TkWordFormInBlankFragment;
import com.ssyc.gsk_tk.util.TimeCount;
import com.ssyc.gsk_tk.util.TkKeys;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 题库主界面
 */
@Route(path = "/tk/TkMainActivity")
public class TkMainActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private ImageView ivBack;
    private RelativeLayout rlChooseNum;
    private RelativeLayout rlLoading;
    private RelativeLayout rlContent;
    private LinearLayout ll_timer;

    private int SUBMIT = 1000000;
    //计时器
    private Chronometer timer;

    //进度条
    private ZzHorizontalProgressBar pb;

    //显示进度条的文本
    private TextView tvPb;

    private SuperViewPager vp;

    //填充的Fragment集合
    private List<Fragment> mFragments;
    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录ViewPager的页面位置值
    private int currPos = 0;

    //控制顶部的答题面板是否可以点击的标识
    private boolean isArrowClick = false;


    //提交面板的数据模型
    private List<PanelInfo> panelInfos;
    private TkHomeWorkInfo.HomeworkBean info;

    //是否需要重新计时的标识
    public static boolean isNeedCountTime = true;

    //设置isNeedCountTime的方法
    public static void setIsNeedCountTime(boolean isNeedCountTime) {
        TkMainActivity.isNeedCountTime = isNeedCountTime;
    }

    //提供给获取计时器控件的方法
    public Chronometer getTimer() {
        return timer;
    }

    public void setTimer(Chronometer timer) {
        this.timer = timer;
    }

    {
        //初始化计时器
        TimeCount.init();
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_tk_main;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //接收数据
        initIntent();

    }

    /**
     * 接收数据
     */
    private void initIntent() {

        String infoJson = getIntent().getStringExtra("infoJson");

        info = GsonUtil.jsonToBean(infoJson, TkHomeWorkInfo.HomeworkBean.class);

        if (null != info && "0".equals(info.getIsdone())) {
            //请求未完成的服务器获取数据
            httpNoComplete();
            //启动计时器
            TimerCountManager.startTimer(true, timer);
        } else {
            //请求已经完成的服务器获取数据
            httpCompleted();
            ll_timer.setVisibility(View.GONE);
        }

    }


    /**
     * 初始化视图
     */
    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        rlChooseNum = findViewById(R.id.rl_choose_num);
        rlChooseNum.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        rlLoading = findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);
        pb = findViewById(R.id.pb);
        tvPb = findViewById(R.id.tv_pb);
        rlContent = findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);
        timer = findViewById(R.id.timer);
        ll_timer = findViewById(R.id.ll_timer);

    }

    /**
     * 请求未完成服务器数据的方法
     */
    private void httpNoComplete() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "21");
        map.put("exam_id", info.getExam_id());


        HttpUtils.post(HttpAdress.NOTKQUESTION, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    rlLoading.setVisibility(View.GONE);
                    rlContent.setVisibility(View.VISIBLE);
                    QuestionInfo info = null;

                    try {
                        info = GsonUtil.jsonToBean(response, QuestionInfo.class);

                        Log.i("test", "列表:" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if (1 == info.getState()) {
                            //状态码为1返回成功
                            //取list对象
                            QuestionInfo.ListBean bean = info.getList();

                            if (null != bean) {
                                //取所有的题型数据
                                List<QuestionInfo.ListBean.ItemBean> item = bean.getItem();

                                //根据返回的题型来初始化Fragment
                                initFragments(item);

                                //初始化提交面板的数据
                                initNoCompletePaneInfos(item);
                            }
                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("服务器异常", false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }
            }
        });
    }


    /**
     * 根据返回的所有题型来创建Fragement
     *
     * @param item
     */
    private void initFragments(List<QuestionInfo.ListBean.ItemBean> item) {

        //创建Fragment集合
        mFragments = new ArrayList<>();

        //选词填空(TkChooseWordInBlankFragment)和用单词的适当形式填空(TkWordFormInBlankFragment)
        //遍历集合创建Fragment集合
        if (item != null && item.size() != 0) {
            for (int i = 0; i < item.size(); i++) {
                if (item.get(i).getTypeid() == 1) {

                } else if (item.get(i).getTypeid() == 2) {

                } else if (item.get(i).getTypeid() == 3) {
                    //阅读
                    mFragments.add(TkReadFragment.newInstance(item.get(i), null));

                } else if (item.get(i).getTypeid() == 4) {

                } else if (item.get(i).getTypeid() == 5) {
                    //完形填空
                    mFragments.add(TkClozeTestFragment.newInstance(item.get(i), null));

                } else if (item.get(i).getTypeid() == 6) {

                } else if (item.get(i).getTypeid() == 7) {
                    //用单词的适当形式填空
                    mFragments.add(TkWordFormInBlankFragment.newInstance(item.get(i), null));

                } else if (item.get(i).getTypeid() == 8) {
                    //句子改错
                    mFragments.add(TkSentenceChangeErrorFragment.newInstance(item.get(i), null));

                } else if (item.get(i).getTypeid() == 9) {
                    //翻译题
//                  mFragments.add(TkTranslateFragment.newInstance());

                } else if (item.get(i).getTypeid() == 10) {
                    //单选题
                    mFragments.add(TkSingleChoiceFragment.newInstance(item.get(i), null));

                } else if (item.get(i).getTypeid() == 11) {

                } else if (item.get(i).getTypeid() == 12) {
                    //句子转换
//                    mFragments.add(TksentenceTransitionFragment.newInstance());

                } else if (item.get(i).getTypeid() == 13) {
                    //选词填句子
                    mFragments.add(TkGapFillingFragment.newInstance(item.get(i), null));

                } else if (item.get(i).getTypeid() == 14) {
                    //选词填文章
                    mFragments.add(TkChooseWordInArticleFragment.newInstance(item.get(i), null));
                }
            }

            //初始化Vp的操作
            if (mFragments.size() != 0) {

                //设置默认进度条的值
                pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));

                //设置当前展示的Vp的页码
                tvPb.setText("1/" + (mFragments.size()));

                initVp();

                //设置Vp的监听
                vp.addOnPageChangeListener(this);
            }
        }
    }

    /**
     * 初始化Vp的操作
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //记录当前ViewPager的位置
        currPos = position;

        //设置进度条的文本显示值
        tvPb.setText((position + 1) + "/" + (mFragments.size()));

        //同时需要设置进度条的值
        pb.setProgress((int) ((float) (position + 1) / (float) (mFragments.size()) * 100));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.rl_choose_num) {
            if (isArrowClick) {
                //弹出选择题目的PopWindow
                showAnswerQuestionPop();
            } else {
                UiUtils.Toast("正在加载数据,请稍候...", false);
            }
        }
    }

    /**
     * 初始化提交面板的数据
     *
     * @param item
     */
    private void initNoCompletePaneInfos(List<QuestionInfo.ListBean.ItemBean> item) {
        panelInfos = new ArrayList<>();
        for (int i = 0; i < item.size(); i++) {
            PanelInfo panelInfo = new PanelInfo();
            panelInfo.question_id = item.get(i).getId_D() + "";
            panelInfo.question_type = item.get(i).getTypeid() + "";
            //默认都是未完成的状态
            panelInfo.state = 0;
            //默认给0,检查大题的所有小题,如果所有小题都回答正确,该值给1,如果所有小题有一个题,则该值给0
            panelInfo.qa_answer = 0;

            List<CommitAnswerInfo> commitAnswerInfos = new ArrayList<>();
            //获取每个答题对应的小题的json数据
            String jsonData = item.get(i).getContent();
            if (!TextUtils.isEmpty(jsonData)) {
                if (item.get(i).getTypeid() == 1) {

                } else if (item.get(i).getTypeid() == 2) {

                } else if (item.get(i).getTypeid() == 3) {
                    //阅读
                    ReadInfo readInfo = GsonUtil.jsonToBean(jsonData, ReadInfo.class);
                    List<ReadInfo.ListBean> readInfoList = readInfo.getList();
                    for (int j = 0; j < readInfoList.size(); j++) {
                        CommitAnswerInfo info = new CommitAnswerInfo();
                        info.isRight = false;//默认错误
                        info.num = j + "";//编号
                        info.score = 2;//没小题的分数
                        info.rightAnser = readInfoList.get(j).getR();//正确答案
                        info.onwAnswer = "";//自己的答案,默认是空
                        commitAnswerInfos.add(info);
                    }
                } else if (item.get(i).getTypeid() == 4) {

                } else if (item.get(i).getTypeid() == 5) {
                    //完形填空
                    ReadInfo readInfo = GsonUtil.jsonToBean(jsonData, ReadInfo.class);
                    List<ReadInfo.ListBean> readInfoList = readInfo.getList();
                    for (int j = 0; j < readInfoList.size(); j++) {
                        CommitAnswerInfo info = new CommitAnswerInfo();
                        info.isRight = false;//默认错误
                        info.num = j + "";//编号
                        info.score = 1;//没小题的分数
                        info.rightAnser = readInfoList.get(j).getR();//正确答案
                        info.onwAnswer = "";//自己的答案,默认是空
                        commitAnswerInfos.add(info);
                    }
                } else if (item.get(i).getTypeid() == 6) {

                } else if (item.get(i).getTypeid() == 7) {
                    //用单词的适当形式填空
                    BlankInfo blankInfo = GsonUtil.jsonToBean(jsonData, BlankInfo.class);
                    List<String> list = blankInfo.getList();
                    for (int j = 0; j < list.size(); j++) {
                        CommitAnswerInfo info = new CommitAnswerInfo();
                        info.isRight = false;//默认错误
                        info.num = j + "";//编号
                        info.score = 1;//没小题的分数
                        info.rightAnser = list.get(j);//正确答案
                        info.onwAnswer = "";//自己的答案,默认是空
                        commitAnswerInfos.add(info);
                    }
                } else if (item.get(i).getTypeid() == 8) {
                    //句子改错只有一个题型
                    SentenceInfo sentenceInfo = GsonUtil.jsonToBean(jsonData, SentenceInfo.class);
                    String right = sentenceInfo.getRight();
                    CommitAnswerInfo info = new CommitAnswerInfo();
                    info.isRight = false;//默认错误
                    info.num = 0 + "";//编号
                    info.score = 1;//没小题的分数
                    info.rightAnser = right;//正确答案
                    info.onwAnswer = "";//自己的答案,默认是空
                    commitAnswerInfos.add(info);

                } else if (item.get(i).getTypeid() == 9) {
                    //翻译题

                } else if (item.get(i).getTypeid() == 10) {
                    //单选题只有一个题型
                    CommitAnswerInfo info = new CommitAnswerInfo();
                    info.isRight = false;//默认错误
                    info.num = 0 + "";//编号
                    info.score = 1;//没小题的分数
                    info.onwAnswer = "";//自己的答案,默认是空
                    commitAnswerInfos.add(info);

                } else if (item.get(i).getTypeid() == 11) {

                } else if (item.get(i).getTypeid() == 12) {
                    //句子转换

                } else if (item.get(i).getTypeid() == 13) {
                    //选词填句子
                    GapFillingInfo articleInfo = GsonUtil.jsonToBean(jsonData, GapFillingInfo.class);
                    List<GapFillingInfo.ListBean> list = articleInfo.getList();
                    for (int j = 0; j < list.size(); j++) {
                        CommitAnswerInfo info = new CommitAnswerInfo();
                        info.isRight = false;//默认错误
                        info.num = j + "";//编号
                        info.score = 1;//没小题的分数
                        info.rightAnser = list.get(j).getA();//正确答案
                        info.onwAnswer = "";//自己的答案,默认是空
                        commitAnswerInfos.add(info);
                    }
                } else if (item.get(i).getTypeid() == 14) {
                    //选词填文章
                    ArticleInfo articleInfo = GsonUtil.jsonToBean(jsonData, ArticleInfo.class);
                    List<ArticleInfo.ListABean> listA = articleInfo.getListA();
                    for (int j = 0; j < listA.size(); j++) {
                        CommitAnswerInfo info = new CommitAnswerInfo();
                        info.isRight = false;//默认错误
                        info.num = j + "";//编号
                        info.score = 2;//没小题的分数
                        info.rightAnser = listA.get(j).getTxtA();//正确答案
                        info.onwAnswer = "";//自己的答案,默认是空
                        commitAnswerInfos.add(info);
                    }
                }
            }
            panelInfo.commitAnswerInfos = commitAnswerInfos;
            panelInfos.add(panelInfo);
            //面板数据加载完成后可以点击
            isArrowClick = true;
        }
    }

    /**
     * 显示提交面板的PopUpwindow
     */
    private void showAnswerQuestionPop() {
        PopUpManager.showPop(this, R.layout.tk_commit_answer, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                MyGridView mGv = view.findViewById(R.id.gv);
                Button btCommit = view.findViewById(R.id.bt_commit);
                if (null != info && "0".equals(info.getIsdone())) {
                    btCommit.setVisibility(View.VISIBLE);
                } else {
                    btCommit.setVisibility(View.GONE);
                }

                PanelGvAdapter panelGvAdapter = new PanelGvAdapter(TkMainActivity.this, panelInfos, R.layout.tk_gv_item_panel);
                mGv.setAdapter(panelGvAdapter);
                panelGvAdapter.setOnTvClickListener(new PanelGvAdapter.onTvClickListener() {
                    @Override
                    public void onClick(int pos) {
                        //关闭弹框
                        PopUpManager.dismiss();
                        //回调位置,Vp跳转到相对应的点击位置
                        currPos = pos;
                        vp.setCurrentItem(currPos);
                    }
                });

                btCommit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //提交按钮
                        //先判断是否允许提交的条件,所有大题的小题都做完了才允许提交
                        if (!hasDoneOver(panelInfos)) {
                            UiUtils.Toast("未完成答题,不能进行提交", false);
                            return;
                        } else {
                            PopUpManager.dismiss();
                            String time = getPostTime();

                            int scoretemp = (int) ((Double.parseDouble(getMyScore(panelInfos))
                                    / Double.parseDouble(getTotalScore(panelInfos))) * 100);
                            //获取总正确率
                            String score = scoretemp+"";

//                            Log.i("test", "我的成绩：" + getMyScore(panelInfos));
//                            Log.i("test", "总分：" + getTotalScore(panelInfos));
//                            Log.i("test", "总分：" +score);

                            //上传的json数据
                            String postJson = getPostJson(panelInfos);

                            CustomDialogManager.show(TkMainActivity.this, "上传中...");
                            Map<String, String> map = new HashMap<>();
                            map.put("type", "10");
                            map.put("ttel", info.getTeacher());
                            map.put("stel", info.getStudent());
                            map.put("sname", info.getSname());
                            map.put("num", info.getClassnum() + "");
                            map.put("exam_id", info.getExam_id());
                            map.put("total_time", time);
                            map.put("score", score);
                            map.put("usedfor", "1");
                            map.put("question_list", postJson);

                            Log.i("test", "type=10&ttel=" + info.getTeacher() + "&stel=" + info.getStudent()
                                    + "&sname=" + info.getSname() + "&num=" + info.getClassnum() + "&exam_id=" + info.getExam_id()
                                    + "&total_time=" + time + "&score=" + score + "&usedfor=1&question_list=" + postJson);

                            HttpUtils.post(HttpAdress.TKCOMMIT, map, this, new HttpUtils.CallBack() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    CustomDialogManager.dissmiss();
                                    UiUtils.Toast(BaseApplication.ERROR, false);
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    CustomDialogManager.dissmiss();
                                    ResultInfo info = null;
                                    if (!TextUtils.isEmpty(response)) {
                                        try {
                                            info = GsonUtil.jsonToBean(response, ResultInfo.class);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Log.i("test", "数据解析异常");
                                        }
                                        Log.i("test", "题库提交返回的json：" + response);

                                        if (info != null) {
                                            if ("1".equals(info.state)) {
                                                //上传成功
                                                UiUtils.Toast("提交成功", false);

                                                BusInfo busInfo = new BusInfo();
                                                busInfo.tkMsg = SUBMIT;
                                                EventBus.getDefault().post(busInfo);
                                                //关闭页面
                                                finish();
                                            } else {
                                                UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                                                Log.i("test", "错误码是:" + info.state);
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }
                });
            }
        });
    }

    /**
     * 考虑熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();

        TimerCountManager.stopTimer(timer);

        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);
    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();

        if (isNeedCountTime) {
            TimerCountManager.startTimer(false, timer);
        }

        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }


    /**
     * 生命周期中停止计时
     */
    @Override
    protected void onDestroy() {

        //销毁时停止计时
        TimerCountManager.stopTimer(timer);

        //还原状态
        setIsNeedCountTime(true);

        //还原计时器的时间统计
        TimeCount.release();

        super.onDestroy();
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.tkMsg == TkKeys.TKMsg) {
            //取出当前Vp所在的页面的大题对象
            PanelInfo info = panelInfos.get(currPos);
            List<CommitAnswerInfo> commitAnswerInfos = info.commitAnswerInfos;
            //取出作答的小题对象,同步当前小题的作答信息
            int pos = busInfo.tkChoosePos;
            CommitAnswerInfo answerInfo = commitAnswerInfos.get(pos);
            answerInfo.setOnwAnswer(busInfo.tkChooseAnswer);
            answerInfo.setRight(busInfo.tkChooseResult);

            //同步info的状态
            //是否完成的状态同步
            if (hasCompeted(commitAnswerInfos)) {
                //已经做完
                info.state = 1;
            } else {
                //没有做完
                info.state = 0;
            }

            //总分的状态同步
            info.score = getScore(commitAnswerInfos);

            //是否正确的状态同步qa_answer的值
            if (isAllRight(commitAnswerInfos)) {
                info.qa_answer = 1;
            } else {
                info.qa_answer = 0;
            }

            //同步大题中每个小题的正确率
            info.sub_answer = sysSubAnswer(commitAnswerInfos);

            //同步大题中每个小题的具体答案
            info.option_content = sysOptionContent(commitAnswerInfos);
        }
    }


    /**
     * 根据小题是否都作答判断该答题是否做完的方法
     * 返回true做完,返回false没做完
     * 只要小题中onwAnswer有一个是空,则返回false
     */
    public boolean hasCompeted(List<CommitAnswerInfo> commitAnswerInfos) {
        boolean res = true;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (TextUtils.isEmpty(commitAnswerInfos.get(i).onwAnswer)) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 根绝每个小题返回当前答题的分数
     * 先判断当前小题是否作答正确,如果正确,则加上该小题的分数
     */
    public int getScore(List<CommitAnswerInfo> commitAnswerInfos) {
        int res = 0;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (commitAnswerInfos.get(i).isRight) {
                //作答正确
                res += commitAnswerInfos.get(i).score;
            }
        }
        return res;
    }


    /**
     * 根据小题是否都正确来判断该大题是否正确的方法
     * 返回true全部正确,返回false则错误
     * 只要小题中onwAnswer有一个是空,则返回false
     */
    public boolean isAllRight(List<CommitAnswerInfo> commitAnswerInfos) {
        boolean res = true;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (!commitAnswerInfos.get(i).isRight) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 同步大题中每个小题的具体答案的方法
     * 将每个小题的用户自己作答的信息使用￠连接拼串
     */
    public String sysOptionContent(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                res += commitAnswerInfos.get(i).onwAnswer;
            } else {
                //其它,使用￠+当前自己的作答进行连接
                res += "￠" + commitAnswerInfos.get(i).onwAnswer;
            }
        }
        return res;
    }


    /**
     * 同步大题中每个小题的对错的方法
     * 将每个小题的用户的作答对错使用￠连接拼串
     */
    public String sysSubAnswer(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                if (commitAnswerInfos.get(i).isRight) {
                    res += "1";
                } else {
                    res += "0";
                }
            } else {
                //其它,使用￠+当前自己的作答进行连接

                if (commitAnswerInfos.get(i).isRight) {
                    res += "￠" + "1";
                } else {
                    res += "￠" + "0";
                }
            }
        }
        return res;
    }


    /**
     * 获取上传的总分数的方法
     * 上传的key为score
     */
    public String getTotalScore(List<PanelInfo> panelInfos) {
        int res = 0;
        for (int i = 0; i < panelInfos.size(); i++) {

            List<CommitAnswerInfo> commitAnswerInfos = panelInfos.get(i).commitAnswerInfos;

            for (int j = 0; j < commitAnswerInfos.size(); j++) {
                res += commitAnswerInfos.get(j).score;
            }
        }
        return res + "";
    }

    /**
     * 获取获得分数的方法
     * 上传的key为score
     */
    public String getMyScore(List<PanelInfo> panelInfos) {
        int res = 0;
        for (int i = 0; i < panelInfos.size(); i++) {

            List<CommitAnswerInfo> commitAnswerInfos = panelInfos.get(i).commitAnswerInfos;

            for (int j = 0; j < commitAnswerInfos.size(); j++) {
                if (commitAnswerInfos.get(j).isRight) {
                    res += commitAnswerInfos.get(j).score;
                }
            }
        }
        return res + "";
    }

    /**
     * 获取上传的时间的方法,返回的是秒
     */
    public String getPostTime() {

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        return seconds;
    }

    /**
     * 上传的key为question_list
     * 根据提交面板的数据生成提交需要的json格式数据的方法
     */
    public String getPostJson(List<PanelInfo> panelInfos) {
        List<CommitInfo> commitInfos = new ArrayList<>();
        for (int i = 0; i < panelInfos.size(); i++) {
            CommitInfo info = new CommitInfo();
            info.option_content = panelInfos.get(i).option_content;
            info.qa_answer = panelInfos.get(i).qa_answer;
            info.question_type = panelInfos.get(i).question_type;
            info.question_id = panelInfos.get(i).question_id;
            info.sub_answer = panelInfos.get(i).sub_answer;

            commitInfos.add(info);
        }

        return GsonUtil.listToJson(commitInfos);
    }


    /**
     * 判断所有大题是否做完的方法
     */
    public boolean hasDoneOver(List<PanelInfo> panelInfos) {
        boolean res = true;
        for (int i = 0; i < panelInfos.size(); i++) {
            if (panelInfos.get(i).state == 0) {
                res = false;
                break;
            }
        }
        return res;
    }



    /*-------------------------------------以完成接入题库的操作--------------------------------------------------*/

    /**
     * 请求已完成服务器数据的方法
     */
    private void httpCompleted() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "12");
        map.put("exam_id", info.getExam_id());
        Log.i("test", info.getExam_id());
        HttpUtils.post(HttpAdress.TKQUESTION, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    rlLoading.setVisibility(View.GONE);
                    rlContent.setVisibility(View.VISIBLE);
                    OverQuestion info = null;

                    Log.i("test", response);

                    try {
                        info = GsonUtil.jsonToBean(response, OverQuestion.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if (1 == info.getState()) {
                            //状态码为1返回成功
                            //取list对象
                            List<OverQuestion.ListBean> beans = info.getList();

                            if (null != beans) {
                                //取所有的题型数据
                                List<OverQuestion.ListBean.ItemBean> item = beans.get(0).getItem();

                                //根据返回的题型来初始化Fragment
                                initOverFragments(item);

                                //初始化提交面板的数据
                                initOverCompletePaneInfos(item);
                            }
                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("服务器异常,返回异常码是:" + info.getState(), false);
//                            Log.i("test", "返回异常码是:" );
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化以完成的弹出面板的数据
     *
     * @param item
     */
    private void initOverCompletePaneInfos(List<OverQuestion.ListBean.ItemBean> item) {
        panelInfos = new ArrayList<>();
        for (int i = 0; i < item.size(); i++) {
            PanelInfo panelInfo = new PanelInfo();
            //以完成进来都是以完成度状态
            panelInfo.state = 1;
            panelInfos.add(panelInfo);
        }
        //面板数据加载完成后可以点击
        isArrowClick = true;
    }


    /**
     * 根据返回的所有题型来创建Fragement
     *
     * @param item
     */
    private void initOverFragments(List<OverQuestion.ListBean.ItemBean> item) {

        //创建Fragment集合
        mFragments = new ArrayList<>();

        //选词填空(TkChooseWordInBlankFragment)和用单词的适当形式填空(TkWordFormInBlankFragment)
        //遍历集合创建Fragment集合
        if (item != null && item.size() != 0) {
            for (int i = 0; i < item.size(); i++) {
                if (item.get(i).getTypeid() == 1) {

                } else if (item.get(i).getTypeid() == 2) {

                } else if (item.get(i).getTypeid() == 3) {
                    //阅读
                    mFragments.add(TkReadFragment.newInstance(null, item.get(i)));

                } else if (item.get(i).getTypeid() == 4) {

                } else if (item.get(i).getTypeid() == 5) {
                    //完形填空
                    mFragments.add(TkClozeTestFragment.newInstance(null, item.get(i)));

                } else if (item.get(i).getTypeid() == 6) {

                } else if (item.get(i).getTypeid() == 7) {
                    //用单词的适当形式填空
                    mFragments.add(TkWordFormInBlankFragment.newInstance(null, item.get(i)));

                } else if (item.get(i).getTypeid() == 8) {
                    //句子改错
                    mFragments.add(TkSentenceChangeErrorFragment.newInstance(null, item.get(i)));

                } else if (item.get(i).getTypeid() == 9) {
                    //翻译题

                } else if (item.get(i).getTypeid() == 10) {
                    //单选题
                    mFragments.add(TkSingleChoiceFragment.newInstance(null, item.get(i)));

                } else if (item.get(i).getTypeid() == 11) {

                } else if (item.get(i).getTypeid() == 12) {
                    //句子转换

                } else if (item.get(i).getTypeid() == 13) {
                    //选词填句子
                    mFragments.add(TkGapFillingFragment.newInstance(null, item.get(i)));

                } else if (item.get(i).getTypeid() == 14) {
                    //选词填文章
                    mFragments.add(TkChooseWordInArticleFragment.newInstance(null, item.get(i)));
                }
            }

            //初始化Vp的操作
            if (mFragments.size() != 0) {

                //设置默认进度条的值
                pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));

                //设置当前展示的Vp的页码
                tvPb.setText("1/" + (mFragments.size()));

                initVp();

                //设置Vp的监听
                vp.addOnPageChangeListener(this);
            }
        }
    }
}
